import { View, Text, Image,ScrollView } from '@tarojs/components'
import Taro,{ useLoad } from '@tarojs/taro'
import './index.scss'
import React, { useEffect, useState } from 'react'
import type { MerchantType } from '../../../types/userData'

import { AtIcon } from 'taro-ui'

import mockMerchants from '../../mock/mockMerchants'


const merchants: MerchantType[] = mockMerchants.filter(merchant => 
  merchant.category === '通讯账户' || 
  merchant.category === '商超账户' || 
  merchant.category === '本地生活'
)

const categoryList = ['通讯账户','商超账户', '本地生活']





export default function MerchantList () {
  // 添加loading图片
  const [loadingImgs] = useState(['https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/load_1.png', 'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/load_2.png', 'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/load_3.png', 'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/load_4.png', 'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/load_5.png'])
  const [loading, setLoading] = useState(true)
  const [selectedMerchantIds, setSelectedMerchantIds] = useState(merchants.map((item) => item.id));
  const [modalVisible, setModalVisible] = useState(false);
  const [curImageIndex, setCurImageIndex] = useState(0);
  let timer = '' as any
  useEffect(() => {
    timer = setInterval(()=>{
      setCurImageIndex(curImageIndex=>{
        if(curImageIndex === loadingImgs.length - 2){
          setLoading(false)
          clearInterval(timer)
        }
        return (curImageIndex + 1) % loadingImgs.length
      })
    },1000)
  },[loadingImgs])

  function getIconValue(category: string) {
    switch (category) {
      case '通讯账户':
        return 'iphone';
      case '商超账户':
        return 'shopping-bag';
      case '本地生活':
        return 'map-pin';
      default:
        return '';
    }

  }
  function getCategoryNum(category: string){
    return merchants.filter(merchant => merchant.category === category).length
  }
 
  function toggleMerchantId(id: string) {
    console.log('toggleMerchantId id:',id)
    if (selectedMerchantIds.includes(id)) {
      setSelectedMerchantIds((prevSelectedMerchantIds) =>
        prevSelectedMerchantIds.filter((merchantId) => merchantId !== id)
      );
    }else {
      setSelectedMerchantIds((prevSelectedMerchantIds) => [...prevSelectedMerchantIds, id]);
    }
  }
  function handleBind(){
    Taro.showLoading({
      title: '绑定中，请稍等',
    })
    setTimeout(() => {
      Taro.hideLoading()
      Taro.navigateTo({
        url: '/pages/bindSuccess/index'
      })
    }, 1000);
  }
  return (
    <View className='merchantList'>
      <View className='header'>
        <View className="title" style={{ alignItems: 'center', marginTop: 30 }}>
          <Text style={{ fontSize: 24, textAlign: 'center',   fontWeight: 'bold' }}>选择积分账户</Text>
        </View>
        <View className='sub-title'>
          <Text>
            查询到以下积分账户，请选择
          </Text>
        </View>
      </View>
      <View className='body'>
      {loading && (
        <>
        <View className='loading-image-wrap'>
          <View style={{
            height: 80,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
            {loadingImgs.map((imageSrc, index) => (
              <Image
                className={['loading-image',index===curImageIndex ? 'show':'hide'].join(' ')}
                key={index}
                src={imageSrc}
                mode='aspectFit'
              />
            ))}
          </View>
        </View>
        <View className='loading-text'>
          正在查询可绑定账户
        </View>
        </>
      )}
      {
        !loading && (
          <ScrollView scrollY>
            <View className='category'>
              {categoryList.map(category=>{
                return (
                  <View className='category-item' key={category}>
                    <View className='category-title'>
                      <AtIcon value={getIconValue(category)} size='10' color='#E83B2F'></AtIcon>
                      <Text className='title-text'>{category}({getCategoryNum(category)})</Text>
                    </View>
                    <View className='mer-list'>
                      {merchants.filter((merchant) => merchant.category === category).map((merchant,index) => {
                        return (
                          <View className='merchant-item' key={merchant.id} onClick={toggleMerchantId.bind(this, merchant.id)}>
                            <View className='merchant-image-box'>
                              <Image className='merchant-image' src={merchant.image} mode='aspectFit' />
                            </View>
                            
                            <View className='merchant-info'>
                              <View className='merchant-name'>{merchant.name}</View>
                              <View className='merchant-points'>    
                                <AtIcon value='sketch' size='10' color='#E83B2F'></AtIcon>
                                <Text className='merchant-points-text'>{merchant.points}</Text>
                              </View>
                            </View>
                            
                            {selectedMerchantIds.includes(merchant.id) && <View className='merchant-checkbox'><AtIcon value='check-circle' size='20' color='green'></AtIcon></View>}
                            
                            </View>
                        )
                      })}
                    </View>
                  </View>
                )
              })}
            </View>
            <View className='bind-btn' onClick={handleBind}>
              绑定
            </View>
          </ScrollView>
        )
        
      }
      </View>
    </View>
  )
}
